from pathlib import Path
import re
from core.backup import BackupManager
from plugins.template.adapter import PluginBase

class OpenSUSEAdapter(PluginBase):
    def __init__(self):
        self.repo_dir = Path("/etc/zypp/repos.d/")
        self.backup = BackupManager("opensuse")

    @classmethod
    def is_compatible(cls) -> bool:
        return OpenSUSEDetector().detect()

    def apply_mirror(self, mirror_url: str):
        """替换所有 .repo 文件的 baseurl"""
        for repo_file in self.repo_dir.glob("*.repo"):
            self.backup.create(repo_file)
            content = repo_file.read_text()
            
            # 替换清华镜像
            content = re.sub(
                r"^baseurl=http://download.opensuse.org/(.*)",
                f"baseurl={mirror_url}/opensuse/\\1",
                content,
                flags=re.MULTILINE
            )
            repo_file.write_text(content)